<template>
  <div class="home st-content">
    <st-block>
      <div class="home-title">注册下载运天下</div>

      <van-form style="width: 100%" @submit="onSubmit">
        <div class="input-border">
          <van-field
            v-model="userTypeText"
            is-link
            readonly
            name="picker"
            label=""
            placeholder="请选择您的身份"
            :border="false"
            :rules="[{ required: true, message: '请选择您的身份' }]"
            @click="showPicker = true"
          />
        </div>
        <div class="input-border">
          <van-field
            v-model="mobile"
            name="mobile"
            type="tel"
            label=""
            placeholder="请输入您的手机号"
            :border="false"
            :maxlength="11"
            :rules="[
              { required: true, message: '请填写手机号' },
              {
                pattern: /^1\d{10}$/,
                message: '请填写正确手机号',
                trigger: ['onChange', 'onBlur', 'onSubmit']
              }
            ]"
          />
        </div>
        <div class="input-border">
          <van-field
            v-model="captcha"
            center
            clearable
            name="captcha"
            label=""
            placeholder="请输入短信验证码"
            :border="false"
            :rules="[{ required: true, message: '请输入短信验证码' }]"
          >
            <template #button>
              <van-button
                class="captcha-btn"
                size="small"
                type="primary"
                :loading="loadingCaptcha"
                :loading-text="loadingText"
                @click="sendCaptchaHandle"
                >发送验证码</van-button
              >
            </template>
          </van-field>
        </div>

        <div style="margin-top: 26px">
          <van-button round block type="primary" native-type="submit"> 注册下载体验 </van-button>
        </div>
      </van-form>
    </st-block>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '/@/store/user';
import { sendValidate, registe as registeApi } from '/@/api/system/user';
import { Toast } from 'vant';
import { reactive } from 'vue';

const userStore = useUserStore();
const router = useRouter();
const showPicker = ref<boolean>(false);
const mobile = ref<string>('');
const userType = ref('');
const userTypeText = ref('');
const columns = reactive([
  { text: '司机', value: '2' },
  { text: '货主', value: '1' }
]);
const onConfirm = (val: any) => {
  userType.value = val.value;
  userTypeText.value = val.text;
  showPicker.value = false;
};

const route = useRoute();
const inviteCode = route.query.invite;

// 验证码相关逻辑
const captcha = ref<string>('');
const loadingCaptcha = ref<boolean>(false);
const loadingSeconds = ref<number>(60);
const loadingText = computed(() => `等待${loadingSeconds.value}秒`);
let timer: any = null;
const calcLoadingSeconds = () => {
  timer = setInterval(() => {
    loadingSeconds.value -= 1;
    localStorage.setItem('loadingSeconds', String(loadingSeconds.value));
    localStorage.setItem('lastTime', String(new Date().getTime()));
    console.log(loadingSeconds.value, 'loadingSeconds');
    if (loadingSeconds.value == 0) {
      loadingCaptcha.value = false;
      if (timer) {
        clearInterval(timer);
      }
    }
  }, 1000);
};
const sendCaptchaHandle = (): void => {
  if (!mobile.value) {
    Toast('请输入手机号');
    return;
  }
  sendValidate(mobile.value, 'register').then((res) => {
    Toast('验证码已发送，注意查收');
  });
  loadingCaptcha.value = true;
  loadingSeconds.value = 60;
  // loadingSeconds.value = 1;
  localStorage.setItem('loadingSeconds', String(loadingSeconds.value));
  calcLoadingSeconds();
};

onMounted(() => {
  if (!!localStorage.getItem('loadingSeconds')) {
    const timeRange = (new Date().getTime() - Number(localStorage.getItem('lastTime'))) / 1000;
    const second = Number(localStorage.getItem('loadingSeconds'));
    const time = Math.round(second - timeRange);

    loadingCaptcha.value = time > 0;
    loadingSeconds.value = time > 0 ? time : 60;
    if (timer) {
      clearInterval(timer);
    }
    if (loadingCaptcha.value) {
      calcLoadingSeconds();
    }
  }
});

const onSubmit = () => {
  registeApi({
    inviteCode,
    userType: userType.value,
    mobile: mobile.value,
    captcha: captcha.value
  })
    .then((res) => {
      if (res.data.code == 200) {
        // window.location.replace('http://share.sdyuntongtianxia.com');
        router.push('/home/dashboard');
      } else {
        Toast(res.data.msg);
      }
      
    })
    .catch((err) => {
      Toast(err.response.data.msg);
    });
};
</script>

<style scoped lang="less">
:deep(.van-loading) {
  display: none !important;
}
.input-border {
  border-radius: 24px;
  border: solid 1px #eeeeee;
  overflow: hidden;
  margin-bottom: 10px;
}
.home {
  padding: 8vh 15px;

  &-title {
    font-weight: var(--van-font-weight-bold);
    font-size: 22px;
    letter-spacing: 2px;
    font-family: PingFangSC-Semibold;
    color: #333;

    margin: 20px auto 50px;
  }
}
.captcha-btn {
  border: solid 1px var(--van-white) !important;
  background: var(--van-white);
  color: #ff6000;
}
</style>
<style scoped>
:root {
  --van-nav-bar-background-color: var(--st-white);
  --van-nav-bar-title-text-color: var(--van-white);
  --van-nav-bar-icon-color: var(--van-white);
  --van-nav-bar-text-color: var(--van-white);
}
</style>
